#include "czhpack.h"
#include <stdlib.h>
#include <string.h>


struct czhpack_item * czhpack_get(const unsigned char *pack,const unsigned char *path)
{
    struct czhpack_item *p = NULL;
    int i,j,k,n;

    if(pack && (path[0]=='/'))
    {
        p = (struct czhpack_item *)pack;
        i = 0;
        while(path[i] && (path[i]=='/'))i++;
        while(path[i])
        {
            j = i;
            while(path[j] && (path[j]!='/'))j++;
            if(j > i)
            {
                n = p->length;
                p = (struct czhpack_item *)(pack + p->offset);
                for(k=0;k<n;k++)
                {
                    if(strncmp(p->name, path+i, ((j-i<=CZHPACK_NAME_SIZE)?(j-i):CZHPACK_NAME_SIZE)) == 0)
                    {
                        break;
                    }
                    p++;
                }
                if(k>=n)//not fond
                {
                    return NULL;
                }
            }
            while(path[j] && (path[j]=='/'))j++;
            i = j;
        }
    }
    return p;
}

void czhpack_list(const unsigned char *pack,const unsigned char *path,void (*visit)(struct czhpack_item *))
{
    struct czhpack_item *p;
    
    p = czhpack_get(pack,path);
    if(p)//fond
    {
        if(p->attribute & CZHPACK_ATTRIBUTE_DIRECTORY)//is directory
        {
            int i,n;

            n = p->length;
            p = (struct czhpack_item *)(pack + p->offset);
            for(i=0;i<n;i++)
            {
                visit(p);
            }
        }
        else//is file
        {
            visit(p);
        }
    }
}

